package com.study.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

//自定义异常返回数据
@Component
public class ClassUrlBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest req, HttpServletResponse resp, BlockException be) throws Exception {
        Map<String, Object> backMap = new HashMap<>();
        if(be instanceof FlowException){
            backMap.put("code", -1);
            backMap.put("msg", "限流异常");
        } else if(be instanceof DegradeException){
            backMap.put("code", -1);
            backMap.put("msg", "降级异常");
        } else if(be instanceof ParamFlowException){
            backMap.put("code", -1);
            backMap.put("msg", "热点参数异常");
        } else if(be instanceof SystemBlockException){
            backMap.put("code", -1);
            backMap.put("msg", "系统规则异常");
        } else if(be instanceof AuthorityException){
            backMap.put("code", -1);
            backMap.put("msg", "授权异常");
        }
        //返回json数据
        resp.setStatus(200);
        resp.setHeader("content-Type","application/json;charset=UTF-8");
        resp.getWriter().write(JSON.toJSONString(backMap));
    }
}
